﻿using System.Configuration;

namespace WordStat
{
    internal class WordStatSettings
    {
        private const string MainAppSection = "MainSettings";

        private Configuration _config;

        public void LoadFromAppConfig()
        {
            _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var section = _config.GetSection(MainAppSection) as CustomSection;

            if (section == null)
            {
                section = new CustomSection();
                _config.Sections.Add(MainAppSection, section);
            }
            else
            {
                _rowNumber = section.RowCount;
            }

            _config.Save();
        }

        public void SaveToAppConfig()
        {
            var section = _config.GetSection(MainAppSection) as CustomSection;

            if (section == null)
            {
                section = new CustomSection();
                _config.Sections.Add(MainAppSection, section);
            }
            else
            {
                section.RowCount = _rowNumber;
            }

            _config.Save();
        }

        private int _rowNumber = 20;
        public int RowNumber
        {
            get { return _rowNumber; }
            set
            {
                if (value <= 0)
                    return;

                _rowNumber = value;
            }
        }
    }

    public sealed class CustomSection : ConfigurationSection
    {
        public CustomSection()
        {
            RowCount = 20;
        }

        [ConfigurationProperty("RowCount", DefaultValue = "20")]
        public int RowCount
        {
            get { return (int)this["RowCount"]; }
            set { this["RowCount"] = value; }
        }
    }
}
